package com.toolmanrln.security.component;

import com.toolmanrln.common.api.ResponseData;
import com.toolmanrln.common.api.dto.TokenDTO;
import com.toolmanrln.common.util.ResponseUtil;
import com.toolmanrln.security.util.JwtTokenUtil;
import com.toolmanrln.security.util.UserDetailsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author ToolMan.RLN
 * @since 2020-05-20 16:01
 */
@Component
public class RestfulAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Value("${jwt.expiration}")
    private Long expiration;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        TokenDTO token = new TokenDTO(jwtTokenUtil.generateToken(UserDetailsUtil.getUserDetails()), LocalDateTime.now().plusSeconds(expiration));
        ResponseUtil.responseToJson(response, ResponseData.success(token));
    }
}
